const db = require("@/db/index");
const config = require("@/utils/config");
const token = require("jsonwebtoken");
const bcrypt = require("bcryptjs");

// 注册
exports.reguser = (req, resp) => {
  const userInfo = req.body;
  const sql = `select * from users where username = ?`;
  db.query(sql, userInfo.username, (err, res) => {
    if (err) return resp.err(err);
    if (res.length > 0) return resp.err("用户名已存在!");
    // 用户密码加密
    userInfo.password = bcrypt.hashSync(userInfo.password, 10);
    const sql = "insert into users set ?";
    db.query(
      sql,
      {
        username: userInfo.username,
        password: userInfo.password,
        role: userInfo.role,
      },
      (err, res) => {
        if (err) return resp.err(err);
        if (res.affectedRows !== 1) return resp.err("注册失败!");
        resp.ok("注册成功");
      }
    );
  });
};

// 登录
exports.login = (req, resp) => {
  const loginInfo = req.body;
  let sql = '';
  if (loginInfo.role == 1) sql = `select * from users where username = ?`;
  if (loginInfo.role == 2) sql = `select * from employee where staff_no = ?`;
  // const sql = `select * from users where username = ?`;
  db.query(sql, loginInfo.username, (err, res) => {
    if (err) return resp.err(err);
    if (res.length !== 1) return resp.err("该用户不存在！");
    // 加密密码验证
    const pwd = bcrypt.compareSync(loginInfo.password, res[0].password);
    if (!pwd) return resp.err("密码错误!");
    const userInfo = { ...res[0], password: null };
    const tokenStr = token.sign(userInfo, config.key, { expiresIn: "10h" });
    const data = {
      userInfo,
      token: tokenStr,
    };
    resp.ok(data);
  });
};
